import { Spin, Menu } from "antd";
import type { MenuProps } from "antd";
import Logo from "./components/Logo";
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import * as Icons from "@ant-design/icons";
import React from "react";
import { connect } from "react-redux";
import { searchRoute, getOpenKeys, findeAllBreadcrumb, handleRouter } from "@/utils/util";
import { setBreadcrumbList } from "@/redux/modules/breadcrumb/action";
import {setMenuListAction} from "@/redux/modules/menu/action";
import { setAuthRouter } from "@/redux/modules/auth/action";
import './index.less'

const LayoutMenu = (props: any) => {
    const { setBreadcrumbList, setMenuListAction, setAuthRouter } = props;
    // 获取当前路径
    const {pathname} = useLocation();
    
    // 折叠菜单的key
    const [openKeys, setOpenKeys] = useState<string[]>([]);
    // 当前选中的key
    const [selectedKeys, setSelectedKeys] = useState<string[]>([pathname]);

    // 定义menu类型
    type MenuItem = Required<MenuProps>["items"][number];
    const getItem = (
        label: React.ReactNode,
        key: string | undefined,
        icon?: React.ReactNode,
        children?: MenuItem[],
        type?: 'group',
    ): MenuItem => {
        return {
            key,
            icon,
            children,
            label,
            type,
        } as MenuItem;
    };

    // 菜单数据
    const [menuList, setMenuList] = useState<MenuItem[]>([])
    const [menuData, setMenuData] = useState<Menu.MenuOptions[]>([])
    // loading
    const [loading, setLoading] = useState(false);
    // 获取菜单
    const getMenuData = () => {
        setLoading(true);
        try {
            // axios获取菜单
            let data: Menu.MenuOptions[] = [
                {
                    path: '/sys',
                    icon: 'SettingOutlined',
                    label: '系统管理',
                    children: [
                        { 
                            path: '/sys/home',
                            label: '用户管理',
                        },
                        { 
                            path: '/sys/home1',
                            label: '用户管理1',
                        }
                    ]
                },
            ]
            setMenuList(deepLoopFloat(data))
            setMenuData(data)
            // 存储处理过后的所有面包屑导航栏到redux中                        
            setBreadcrumbList(findeAllBreadcrumb(data))
            // 把路由菜单处理成一维数组，存储到redux中，做菜单权限判断
            const dynamicRouter = handleRouter(data)
            setAuthRouter(dynamicRouter)
            // 菜单存到redux中
            setMenuListAction(data)
        } finally {
            setLoading(false);
        }
    }
    useEffect(() => {
        getMenuData();
    }, []);
    // 点击当前菜单跳转页面
    const navigate = useNavigate();
    const clickMenu: MenuProps['onClick'] = ({key}: {key: string}) => {
        const route = searchRoute(key, menuData );   
        if(route.isLink) {
            window.open(route.isLink, "_blank")
        } else {
            navigate(key)
        }
    };
    // 折叠菜单-设置当前展开的submenu
    const onOpenChange = (openKeys: string[]) => {
        if(openKeys.length === 0 || openKeys.length === 1) return setOpenKeys(openKeys) ;
        const latestOpenKey = openKeys[openKeys.length - 1];
        if (latestOpenKey.includes(openKeys[0])) {
            setOpenKeys(openKeys);
        } else {
            setOpenKeys([latestOpenKey]);
        }
    };
    // 刷新页面菜单保持高亮
    useEffect(() => {
        setSelectedKeys([pathname]);        
        setOpenKeys(getOpenKeys(pathname))
    }, [pathname]);
    // 动态渲染Icon图标
    const customIcons: {[key: string]: any} = Icons;
    const renderIcon = (icon: string) => {
        if(!icon) return null;
        return React.createElement(customIcons[icon]);
    };

    //  递归渲染菜单，菜单的key为antd菜单需要的key值
    const deepLoopFloat = (menuList: Menu.MenuOptions[], newArr: MenuItem[] = []) => {        
        menuList.forEach((item: Menu.MenuOptions) => {
            if(!item.children?.length) {
                return newArr.push(getItem(item.label, item.path, renderIcon(item.icon!)));
            }
            newArr.push(getItem(item.label, item.path, renderIcon(item.icon!), deepLoopFloat(item.children)));
        });
        return newArr;
    }

    return ( <div className="layout-menu">
        <Logo />
        <Spin spinning={loading} tip="Loading...">
            <Menu 
                theme="dark"
                mode="inline"
                triggerSubMenuAction="click"
                openKeys={openKeys}
                onOpenChange={onOpenChange}
                selectedKeys={selectedKeys}
                items={menuList}
                onClick={clickMenu}
            />
        </Spin>
    </div> );
}

// export default LayoutMenu;
const mapStateToProps = (state: any) => state.menu || {}
const mapDispatchToProps = {setMenuListAction, setBreadcrumbList, setAuthRouter};
export default connect(mapStateToProps, mapDispatchToProps)(LayoutMenu);